const fs = require("fs");
const axios = require("axios");
const qr = require("qrcode-terminal");
const FormData = require("form-data"); // 确保已经安装form-data库：npm install form-data
const { ApiKey, ApiSecret, ReturnUrl } = require("./config");
const image_ref1_path = "./face.png"; // 自行创建人脸图片
let timer,chche_url,
  num = 1;

async function getToken() {
  // 旷视获取token
  // 创建FormData实例
  const formData = new FormData();
  // 添加数据到formData
  formData.append("api_key", ApiKey);
  formData.append("api_secret", ApiSecret);
  formData.append("return_url", ReturnUrl);
  formData.append("notify_url", ReturnUrl);
  formData.append("biz_no", "0");
  formData.append("comparison_type", "0");
  formData.append("idcard_mode", "1");
  formData.append("uuid", Math.random() * 10000);
  formData.append("image_ref1", fs.createReadStream(image_ref1_path));
  formData.append("action_http_method", "GET");

  // 发送POST请求
  axios
    .post("https://api.megvii.com/faceid/lite/get_token", formData)
    .then((res) => {
      console.log(res.data);
      const { token, biz_id } = res.data;
      chche_url = `https://api.megvii.com/faceid/lite/do?token=${token}`
      console.log("生成人脸识别二维码成功！")
      qr.generate(chche_url, {
        small: true,
      }); 
      timer = setInterval(() => {
        console.log(`第${num}次`);
        num++;
        getResult(biz_id);
      }, 5000);
    })
    .catch((error) => {
        handleError(error)
    });
}

function getResult(biz_id) {
  console.log("检测认证结果...");
  axios
    .get(
      `https://api.megvii.com/faceid/lite/get_result?api_key=${ApiKey}&api_secret=${ApiSecret}&biz_id=${biz_id}`
    )
    .then((res) => {
      if (res.data.status == "OK") {
        console.log("结果已返回:");
        clearInterval(timer);
        console.log(res.data);
      } else {
        console.log("未检测到结果！原因:");
        console.log(JSON.stringify(res.data));
      }
    })
    .catch((error) => {
        handleError(error)
    });
}

function handleError(error){
    if (error.response) {
        // 服务器返回了状态码和响应数据
        console.log("Status code:", error.response.status);
        console.log("Response headers:", error.response.headers);
        console.log("Response data:", error.response.data);
        if(error.response.data.error_message == 'DATA_DESTROYED'){
            console.log("检测到15秒没有操作，重新扫码，或者继续操作！")
            qr.generate(chche_url, {
                small: true,
            }); 
        }
    } else if (error.request) {
        // 请求已经发出，但是没有收到响应
        console.error("Request error:", error.request);
    } else {
        // 设置请求时触发错误
        console.error("Error:", error.message);
    }
}

// 参考文档 https://faceid.com/document/faceid-guide-docs/h5_get_token
getToken();
